package com.masterclient.app.businessmodule.minemodule.index.medal;

import android.Manifest;
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieDrawable;
import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.eoner.baselibrary.bean.personal.MedalDetailBean;
import com.eoner.baselibrary.utils.ScreenUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.UIUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.managerlibrary.Tools;
import com.eoner.managerlibrary.weixin.WeiXinManager;
import com.masterclient.app.R;
import com.gyf.immersionbar.ImmersionBar;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;


public class PersonMedalDialog extends Dialog {

    private Activity activity;

    public PersonMedalDialog(Context context) {
        super(context);
    }

    public PersonMedalDialog(Context context, int theme) {
        super(context, theme);
        activity = (Activity)context;
    }

    @Override
    public void show() {
        super.show();
        /**
         * 设置宽度全屏，要设置在show的后面
         */
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.gravity= Gravity.CENTER;
        layoutParams.width= WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height= ScreenUtils.getScreenHeight() - ScreenUtil.getStatusBarHeight();
        getWindow().setWindowAnimations(R.style.dialog_scale_style);
        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        getWindow().setDimAmount(0.4f);
        getWindow().setAttributes(layoutParams);
    }

    @Override
    public void dismiss() {
        if (activity!=null && activity.isFinishing()) {
            return;
        }
        super.dismiss();
    }

    public static class Builder {

        //ui
        private Context mContext;
        private View layout;
        private PersonMedalDialog dialog;

        //关闭按钮
        private ImageView mCloseBtn;
        //背景
        private RelativeLayout mBgView;
        //图片
        private ImageView mBgImageView;
        //标签
        private TextView mTipView;
        //内容
        private TextView mContentView;
        //时间
        private TextView mTimeView;
        //标题
        private TextView mTitleView;
        //副标题
        private TextView mSubTitleView;
        //分享朋友
        private Button mFriendBtn;
        //分享朋友圈
        private Button mCircleBtn;
        //动画
        private LottieAnimationView lottieAnimationView;
        //crop
        private RelativeLayout mCropView;

        //data
        private MedalDetailBean detailBean;
        private @PersonMedalType int medalType;

        private int screenHeight;
        private int designHeight = 2200;

        public Builder setDetailBean(MedalDetailBean detailBean) {
            this.detailBean = detailBean;
            return this;
        }

        public Builder(Context context) {
            this.mContext = context;
            dialog = new PersonMedalDialog(context, R.style.MyDialog);
            dialog.setCancelable(false);
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            layout = inflater.inflate(R.layout.dialog_person_medal, null);
            dialog.addContentView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }

        public PersonMedalDialog create() {
            initUI();
            initData();
            initColor();
            initScale();
            initAction();
            dialog.setContentView(layout);
            dialog.setCancelable(false);
            return dialog;
        }

        private void initUI () {
            lottieAnimationView = layout.findViewById(R.id.medal_animation);
            //关闭按钮
            mCloseBtn = layout.findViewById(R.id.medal_image_close);
            //背景
            mBgView = layout.findViewById(R.id.medal_image_bg);
            //图片
            mBgImageView = layout.findViewById(R.id.medal_image_view);
            //标签
            mTipView = layout.findViewById(R.id.medal_tip_view);
            //内容
            mContentView = layout.findViewById(R.id.medal_content_view);
            //分享朋友
            mFriendBtn = layout.findViewById(R.id.medal_friend_btn);
            //分享朋友圈
            mCircleBtn = layout.findViewById(R.id.medal_circle_btn);
            //时间
            mTimeView = layout.findViewById(R.id.medal_time_view);
            //标题
            mTitleView = layout.findViewById(R.id.medal_title_view);
            //副标题
            mSubTitleView = layout.findViewById(R.id.medal_sub_title_view);
            mCropView = layout.findViewById(R.id.medal_crop_view);

            lottieAnimationView.addAnimatorListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
//
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    //TODO:动画取消
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
        }

        private void initData() {
            //勋章编号 1：显示紫色特效(supter)， 2：显示红色背景(new)
            if (detailBean.data.medal_special_effects != null && detailBean.data.medal_special_effects.equals("1")) {
                medalType = PersonMedalType.MEDAL_SUPER;
                playShopAnimation("super_big.json");
            } else {
                medalType = PersonMedalType.MEDAL_NEW;
                playShopAnimation("new_big.json");
            }
            mTipView.setText("尊敬的:");
            mTimeView.setText(detailBean.data.reward_time);
            mTitleView.setText(detailBean.data.medal_name);
            mSubTitleView.setText(detailBean.data.medal_all_total_desc+"\n"+detailBean.data.medal_way_desc);
        }

        /**
        * 图片宽高 876 * 1125
        * */
        private void initScale() {
            screenHeight = ScreenUtils.getScreenHeight();
            float scale = (screenHeight*1.0f/designHeight*1.0f);
            if (scale <1.0f) {
                //TODO:手机高小于设计高时开始适配 (暂时先不适配)
            }
        }

        private void initColor() {

            SpannableString spannableString = new SpannableString(detailBean.data.reward_content);
            String underLineText = detailBean.data.nick;
            String boldText = detailBean.data.medal_name;
            int color = 0xFF7A3024;
            if (medalType == PersonMedalType.MEDAL_SUPER) {
                color = 0xFF4D0995;
            } else if (medalType == PersonMedalType.MEDAL_NEW) {
                color = 0xFF7A3024;
            }
            mTipView.setTextColor(color);
            mTimeView.setTextColor(color);
            int underLineStart = detailBean.data.reward_content.indexOf(underLineText);
            int boldStart = detailBean.data.reward_content.indexOf(boldText);
            //设置文字的前景色
            spannableString.setSpan(new ForegroundColorSpan(color), 0, detailBean.data.reward_content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (underLineStart >= 0) {
                //设置下划线文字
                spannableString.setSpan(new UnderlineSpan(), underLineStart, underLineStart + underLineText.length(),  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //设置文字加粗
                spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), underLineStart, underLineStart + underLineText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            if (boldStart >= 0) {
                spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), boldStart, boldStart + boldText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            mContentView.setText(spannableString);
        }

        private void initAction() {
            mCloseBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    if (lottieAnimationView != null) {
                        lottieAnimationView.removeAllAnimatorListeners();
                    }
                }
            });
            mFriendBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shareAndSavePic(true);
                }
            });

            mCircleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shareAndSavePic(false);
                }
            });
        }

        private void playShopAnimation(String json) {
            LottieComposition composition = LottieComposition.Factory.fromFileSync(mContext,   json);
            lottieAnimationView.cancelAnimation();
            lottieAnimationView.setProgress(0);
            lottieAnimationView.setRepeatCount(-1);
            lottieAnimationView.setRepeatMode(LottieDrawable.RESTART);
            lottieAnimationView.setComposition(composition);
            lottieAnimationView.playAnimation();
        }

        private static final String APP_ID = "wx8031a358899ba015";
        private RxPermissions rxPermissions;
        @SuppressLint("CheckResult")
        private void shareAndSavePic(boolean isSession){
            if (rxPermissions == null) {
                rxPermissions = new RxPermissions((Activity) mContext);
            }
            rxPermissions
                    .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(permission -> {
                        if (permission.granted) {
                            Bitmap bitmap = toCompositeBitmap(getBitmap());
                            if (bitmap == null) return;
                            String path = UIUtils.getSaveImagePath(mContext, bitmap);
                            if (WeiXinManager.checkVersionValid(mContext) && WeiXinManager.checkAndroidNotBelowN()) {
                                path = WeiXinManager.getFileUri(mContext, new File(path));
                            }
                            if (!TextUtils.isEmpty(path)) {
                                if (Tools.isAppAvilible(mContext,"com.tencent.mm")) {
                                    wxSharePic("he" + System.currentTimeMillis(),isSession,bitmap, path);
                                } else {
                                    ToastUtil.showToast("请先安装微信客户端");
                                }
                            } else {
                                Toast.makeText(mContext, "保存失败", Toast.LENGTH_SHORT).show();
                            }
                            bitmap.recycle();
                        } else if (permission.shouldShowRequestPermissionRationale) {
                        } else {
                            Toast.makeText(mContext, "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                        }
                    });
        }


        public Bitmap getBitmap() {
            View screenView = dialog.getWindow().getDecorView();
            screenView.setDrawingCacheEnabled(true);
            screenView.buildDrawingCache();
            //获取屏幕整张图片
            Bitmap bitmap = screenView.getDrawingCache();
            if (bitmap != null) {
                //需要截取的长和宽
                int outWidth = mCropView.getWidth();
                int outHeight = mCropView.getHeight();
                //获取需要截图部分的在屏幕上的坐标(view的左上角坐标）
                int[] viewLocationArray = new int[2];
                mCropView.getLocationInWindow(viewLocationArray);
                //从屏幕整张图片中截取指定区域
                bitmap = Bitmap.createBitmap(bitmap, viewLocationArray[0], viewLocationArray[1] - ImmersionBar.getStatusBarHeight((Activity) mContext), outWidth, outHeight);
            }

            return bitmap;
        }


        private void wxSharePic(String transaction,boolean isSession,Bitmap bitmap, String path) {
            //初始化WXImageObject和WXMediaMessage对象
            WXImageObject imageObject;
            if (StringUtil.isBlank(path)) {
                imageObject = new WXImageObject();
                imageObject.imagePath = path;
            } else {
                imageObject = new WXImageObject(bitmap);
            }
            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = imageObject;
            //设置缩略图
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
            bitmap.recycle();
            msg.thumbData = Utils.bmpToByteArray(scaledBitmap,false);
            //构造一个Req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = transaction + Long.toString(System.currentTimeMillis());
            req.message = msg;
            //表示发送给朋友圈  WXSceneTimeline  表示发送给朋友  WXSceneSession
            req.scene = isSession ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
            //调用api接口发送数据到微信
            IWXAPI api = WXAPIFactory.createWXAPI(mContext, APP_ID);
            api.sendReq(req);
        }

        public Bitmap toCompositeBitmap(Bitmap foreground) {
            int bgWidth = foreground.getWidth();
            int bgHeight = foreground.getHeight();
            Bitmap newbmp = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
            Canvas cv = new Canvas(newbmp);
            cv.drawColor(mContext.getResources().getColor(R.color.white));
            cv.drawBitmap(foreground, 0, 0, null);
            cv.save();//保存
            return newbmp;
        }

    }

}
